<?php
declare (strict_types = 1);

namespace app\service;

use think\facade\Config;
use think\facade\Log;

class ApiService
{
    /**
     * 调用豆包API生成文案
     */
    public function generateScript($keywords, $poiName, $poiAddress)
    {
        $config = Config::get('doubao');
        $url = $config['api_url'] . '/generate/script';
        
        $data = [
            'keywords' => $keywords,
            'poi_name' => $poiName,
            'poi_address' => $poiAddress,
        ];
        
        $headers = [
            'Authorization' => 'Bearer ' . $config['api_key'],
            'Content-Type' => 'application/json',
        ];
        
        try {
            $response = $this->httpPost($url, json_encode($data), $headers);
            $result = json_decode($response, true);
            
            if (isset($result['code']) && $result['code'] === 0) {
                return $result['data']['script'];
            }
            
            throw new \Exception($result['message'] ?? '生成文案失败');
        } catch (\Exception $e) {
            Log::error('豆包API调用失败：' . $e->getMessage());
            throw $e;
        }
    }
    
    /**
     * 调用抖音POI搜索API
     */
    public function searchPoi($keyword, $latitude = null, $longitude = null)
    {
        $config = Config::get('douyin');
        $url = $config['api_url'] . $config['poi']['search_url'];
        
        $data = [
            'keyword' => $keyword,
            'access_token' => $this->getDouyinAccessToken(),
        ];
        
        if ($latitude && $longitude) {
            $data['latitude'] = $latitude;
            $data['longitude'] = $longitude;
        }
        
        try {
            $response = $this->httpGet($url, $data);
            $result = json_decode($response, true);
            
            if (isset($result['data']['poi_list'])) {
                return $result['data']['poi_list'];
            }
            
            throw new \Exception($result['message'] ?? '搜索POI失败');
        } catch (\Exception $e) {
            Log::error('抖音POI搜索失败：' . $e->getMessage());
            throw $e;
        }
    }
    
    /**
     * 获取抖音POI详情
     */
    public function getPoiDetail($poiId)
    {
        $config = Config::get('douyin');
        $url = $config['api_url'] . $config['poi']['detail_url'];
        
        $data = [
            'poi_id' => $poiId,
            'access_token' => $this->getDouyinAccessToken(),
        ];
        
        try {
            $response = $this->httpGet($url, $data);
            $result = json_decode($response, true);
            
            if (isset($result['data'])) {
                return $result['data'];
            }
            
            throw new \Exception($result['message'] ?? '获取POI详情失败');
        } catch (\Exception $e) {
            Log::error('获取POI详情失败：' . $e->getMessage());
            throw $e;
        }
    }
    
    /**
     * 获取抖音访问令牌
     */
    protected function getDouyinAccessToken()
    {
        $config = Config::get('douyin');
        $url = $config['api_url'] . '/oauth/client_token/';
        
        $data = [
            'client_key' => $config['client_key'],
            'client_secret' => $config['client_secret'],
            'grant_type' => 'client_credentials',
        ];
        
        try {
            $response = $this->httpPost($url, json_encode($data));
            $result = json_decode($response, true);
            
            if (isset($result['access_token'])) {
                return $result['access_token'];
            }
            
            throw new \Exception($result['message'] ?? '获取访问令牌失败');
        } catch (\Exception $e) {
            Log::error('获取抖音访问令牌失败：' . $e->getMessage());
            throw $e;
        }
    }
    
    /**
     * 发送HTTP GET请求
     */
    protected function httpGet($url, $params = [])
    {
        if (!empty($params)) {
            $url .= '?' . http_build_query($params);
        }
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            throw new \Exception('CURL错误：' . $error);
        }
        
        return $response;
    }
    
    /**
     * 发送HTTP POST请求
     */
    protected function httpPost($url, $data, $headers = [])
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        
        if (!empty($headers)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $this->formatHeaders($headers));
        }
        
        $response = curl_exec($ch);
        $error = curl_error($ch);
        curl_close($ch);
        
        if ($error) {
            throw new \Exception('CURL错误：' . $error);
        }
        
        return $response;
    }
    
    /**
     * 格式化请求头
     */
    protected function formatHeaders($headers)
    {
        $formatted = [];
        foreach ($headers as $key => $value) {
            $formatted[] = $key . ': ' . $value;
        }
        return $formatted;
    }
} 